﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AceMobile.Models
{
    public class Cart
    {
        MobileWebContext db = new MobileWebContext();
        public List<Order> Orders { get; set; }
        public int PriceAll = 0;
        public int Amount = 0;
        public Cart(string cart)
        {
            Orders = new List<Order>();
            if (cart.LastIndexOf(";") == -1)
            {
                return;
            }
            string[] listOrder = cart.Split(';');
            
            for (int i = 0; i < listOrder.Length - 1; i++)
			{
                Order order = new Order()
                {
                    ID = Convert.ToInt32(listOrder[i].Split('+')[0]),
                    Type = listOrder[i].Split('+')[1],
                    Amount = Convert.ToInt32(listOrder[i].Split('+')[2])
                };
                Orders.Add(order);
			}
            Amount = getCount();
            PriceAll = getPrice();
        }
        public void addOrder(int id, string Type)
        {
            Order order = new Order()
            {
                ID = id,
                Type = Type,
                Amount = 1
            };
            Orders.Add(order);
        }
        public string tostring()
        {
            string session = "";
            foreach (var item in Orders)
            {
                session += item.ID.ToString() + "+" + item.Type + "+" + item.Amount.ToString() + ";";
            }
            return session;
        }
        public int getCount()
        {
            int i = 0;
            foreach (var item in Orders)
            {
                i += item.Amount;
            }
            return i;
        }
        public int getPrice()
        {
            int price = 0;
            foreach (var item in Orders)
            {
                if (item.Type == "phone")
                {
                    price += item.Amount * db.Phones.Find(item.ID).Price;
                }
                if (item.Type == "accessory")
                {
                    price += item.Amount * db.Accessories.Find(item.ID).Price;
                }
                if (item.Type == "tablet")
                {
                    price += item.Amount * db.Tablets.Find(item.ID).Price;
                }
            }
            return price;
        }
        public static string GetImageFromID(int ID)
        {
            try
            {
                MobileWebContext db = new MobileWebContext();
                return db.Phones.Find(ID).ImageUrl.ToString();
            }
            catch (Exception)
            {
                return "";
            }
            
        }
    }
}